<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            $route.query.id ? '修改文章' : '发布文章'
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form
        ref="publish-form"
        :model="article"
        label-width="60px"
        :rules="formRules"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
          <ElementTiptap
            v-model="article.content"
            :extensions="extensions"
            lang="zh"
            height="300"
            placeholder="请输入文章内容"
          ></ElementTiptap>
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自助</el-radio>
          </el-radio-group>
               <!--
            在组件上使用 v-model
            当你给子组件提供的数据既要使用还要修改时，
            这个时候可以使用 v-model 来简化数据绑定。
            v-model="article.cover.images[index]"
            相当于于下面两句代码：
              (1) v-model 会给子组件传递了一个名字叫value的数据
                :value="article.cover.images[index]"
              (2) v-model 默认还会监听 input 事件
                @input="article.cover.images[index]"
            注意：v-model
            仅仅是简写而已，本质还是在父子组件通信
          -->
           <template v-if="article.cover.type > 0">
            <upload-cover
              v-for="(cover, index) in article.cover.type"
              :key="index"
              v-model="article.cover.images[index]"
            />
          <!-- <template v-if="article.cover.type > 0">
            <upload-cover
              v-for="(cover, index) in article.cover.type"
              :key="index"
              @upload-cover="onUploadCover(index, $event)"
              :cover-image="article.cover.images[index]"
            /> -->
          </template>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择频道">
            <el-option label="请选择频道" :value="null" />
            <el-option
              :label="channel.name"
              :value="channel.id"
              v-for="(channel, index) in channels"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish(false)">{{
            $route.query.id ? '修改' : '发布'
          }}</el-button>
          <el-button @click="onPublish(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getArticleChannels, addArticle, getArticle, updateArticle } from '@/api/article.js'
import { uploadImage } from '@/api/image.js'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TextColor,
  Image,
  Preview,
  Fullscreen
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
import uploadCover from './commponents/uploadCover.vue'
export default {
  name: 'Publish',
  components: {
    ElementTiptap, uploadCover
  },
  props: {},
  data () {
    return {
      channels: [],
      article: {
        title: '', // 文章标题
        content: '', // 文章内容
        cover: { // 文章封面
          type: 0,
          // 封面类型 -1:自动，0-无图，1-1张，3-3张
          images: [] // 封面图潘的地址
        },
        channel_id: null
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // render command-button in bubble menu.
        new Underline({ bubble: true }), // render command-button in bubble menu but not in menubar.
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new TextColor(),
        new Image({
          async uploadRequest (file) {
            const fd = new FormData()
            fd.append('image', file)
            const { data } = await uploadImage(fd)
            // console.log(data)
            // console.log(data.data.url)
            return data.data.url
          }
        }),
        new Preview(),
        new Fullscreen()
      ],
      formRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在 5 到 30 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === '<p></p>') {
                // 验证失败
                callback(new Error('请输入文章内容'))
              } else {
                // 验证通过
                callback()
              }
            }
          }
        ],
        channel_id: [
          { required: true, message: '请输选择文章频道' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.loadChannels()
    // 由于发布和修改都是用的一个组件，所以需要判断
    if (this.$route.query.id) {
      this.loadArticle()
    }
  },
  methods: {
    async loadChannels () {
      const { data } = await getArticleChannels()
      this.channels = data.data.channels
    },
    onPublish (draft) {
      this.$refs['publish-form'].validate(async valid => {
        if (!valid) {
          // 验证失败
          return false
        }
        // 验证成功
        // 如果是修改文章，则执行修改操作，否则就是发布文章
        const articleId = this.$route.query.id
        if (articleId) {
          try {
            await updateArticle(articleId, this.article, draft)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            // 跳转到内容管理页面
            //   this.$router.push('/article')
          } catch (error) {
            console.log('修改失败', error)
          }
        } else {
          try {
            await addArticle(this.article, draft)
            this.$message({
              message: `${draft ? '存入草稿' : '发布'}成功`,
              type: 'success'
            })
            // 跳转到内容管理页面
            this.$router.push('/article')
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    // 修改文章，加载文章内容、
    async loadArticle () {
      const { data } = await getArticle(this.$route.query.id)
      // console.log(data)
      this.article = data.data
    }
    // onUploadCover (index, url) {
    //   // console.log(url)
    //   this.article.cover.images[index] = url
    // }
  }
}
</script>

<style lang="less" scoped>
</style>
